<?php

namespace app\index\controller;

use app\common\model\Document;
use app\common\model\Member as MemberModel;
use app\common\model\Member;
use app\common\model\UcenterMember;
use app\common\controller\Wechat;

use think\Db;
use think\Request;

class Index extends Home
{
    /**
     * 切记：必须是小写字母
     * @var array
     */
    protected $beforeActionList = [
        /*check 不可删除*/
        'check_load' => ['except' => 'login,logout,documentlists,registerindex,getcode,getconfig,getallarea,check,findpwd,getopenid,wechatlogin,loading,setlang,emailindex,uploadimg,addview,getflowrate,slidecode']
    ];

    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 所有配置信息
     */
    public function getConfig()
    {
        $config = config();
        $name = input('name');

        if ($name) {
            $config = config($name);
            if (!$config) {
                $this->apiError('该配置信息不存在！');
            }
        }

        if (is_string($config)) {
            if (strpos($config, ',') !== false) {
                $config = explode(',', $config);
            }
        }
        $this->apiSuccess('配置信息', $config);
    }

    /**
     * 账号/手机号码登录
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login()
    {
        if (!request()->isPost()) {
            $this->apiError('非法操作！');
        }

        $data = input();
        $username = trim($data['username']);
        if (!$username) {
            $this->apiError('账号/手机号码缺失！');
        }

        $userInfo = Db('member')->where('usernumber', $username)->whereOr('mobile', $username)->find();
        if (!$userInfo) {
            $this->apiError('该账户不存在！');
        }

        $type = trim($data['type']);
        switch ($type) {
            case 1:
                $password = trim($data['password']);
                if ('' === $password) {
                    $this->apiError('密码不能为空！');
                }

                if (strlen($password) < 6) {
                    $this->apiError('密码至少六位数');
                }
                $UcenterObj = new UcenterMember();
                $id = $UcenterObj->login($username, $password);
                if ($id <= 0) {
                    $this->apiError('密码错误！');
                }
                break;
            case 2:
                $code = $data['code'];
                if (!$code) {
                    $this->apiError('短信验证码缺失！');
                }
                $res = $this->checkCode($data['mobile'], $data['code']);
                if ($res['status'] == 0) {
                    $this->apiError($res['msg']);
                }
                break;
            default:
                $this->apiError('非法操作！');
                break;
        }

        $token = $this->makeToken($userInfo['uid']);
        if (!$token) {
            $this->apiError('登录失败，请重试！');
        }
        $this->destroyCode($data['mobile']);
        $this->apiSuccess(lang('login successfully!'), ['token' => $token]);
    }

    public function getOpenId()
    {
        $uid = is_login();
        $user = Db('member')->where('uid', $uid)->find();
        if ($user['open_id']) {
            return;
        }
        $wechat = new Wechat();
        $code = input('code');
        if (!$code) {
            $purl = 'http://' . $_SERVER['HTTP_HOST'] . '/index/index/getOpenId';
            $url = $wechat->get_authorize_url($purl);
            header("Location:" . $url);
            exit;
        }
        $data1 = $wechat->get_access_token($code);
        $openId = $data1['openid'];
        $data2 = $wechat->get_token();
        $accessToken = $data2['access_token'];

        $info = $wechat->get_user_info($accessToken, $openId);
        if ($info['subscribe'] == 0) {
            $this->apiError('请先关注公众号！', url('attention'));
        }
        $data = [
            'icon' => $info['headimgurl'],
            'open_id' => $openId,
            'nickname' => $info['nickname'],
            'is_attention' => $info['subscribe']
        ];

        Db('member')->where('uid', $uid)->update($data);
        $this->redirect('User/index');
    }

    /**
     * 微信登录
     */
    public function wechatLogin()
    {
        if (!is_weixin()) {
            $this->apiError('请在微信端打开！');
        }

        $wechat = new Wechat();
        $code = input('code');
        if (!$code) {
            $purl = 'http://' . $_SERVER['HTTP_HOST'] . '/index/Index/wechatLogin';
            $url = $wechat->get_authorize_url($purl);
            header("Location:" . $url);
            exit;
        }
        $wdata = $wechat->get_access_token($code);

        $openId = $wdata['openid'];
        $user = Db('member')->where('open_id', $openId)->find();
        if (!$user) {
            $this->apiError('该会员不存在或者微信信息缺失，请尝试账密登录！');
        }
        if ($user['status'] == -1) {
            $this->apiError('该会员已被冻结！');
        }
        session('user_auth', $user);
        session('user_auth_sign', data_auth_sign($user));

        $this->redirect('User/index');
    }

    /**
     * app下载
     * @return mixed
     */
    public function loading()
    {
        $this->assign('wx', is_weixin());
        $this->assign('title', 'app下载');
        return $this->fetch();
    }

    /**
     * 获取所有的省市县
     */
    public function getAllArea()
    {
        $provinceArray = [];
        $province = Db('district')->where('level', 1)->order('id', 'asc')->select();

        foreach ($province as $key => $value) {
            $area = Db('district')->where('level', 2)->where('pid', $value['cid'])->order('id', 'asc')->select();
            $areaArray = [];
            foreach ($area as $k => $v) {
                $city = Db('district')->where('level', 3)->where('pid', $v['cid'])->order('id', 'asc')->select();
                $cityArray = [];
                if (count($city) == 0) {
                    $cityArray[] = [
                        'id' => 0,
                        'name' => '',
                        'pid' => $v['cid'],
                        'level' => 3
                    ];
                } else {
                    foreach ($city as $city_k => $city_v) {
                        $cityArray[] = [
                            'id' => $city_v['cid'],
                            'name' => $city_v['name'],
                            'pid' => $city_v['pid'],
                            'level' => $city_v['level']
                        ];
                    }
                }

                $areaArray[] = [
                    'id' => $v['cid'],
                    'name' => $v['name'],
                    'pid' => $v['pid'],
                    'level' => $v['level'],
                    'children' => $cityArray
                ];
            }
            $provinceArray[] = [
                'id' => $value['cid'],
                'name' => $value['name'],
                'pid' => 10000,
                'level' => $value['level'],
                'children' => $areaArray
            ];
        }

        $this->apiSuccess('省市区列表', $provinceArray);
    }

    /**
     * 流动池初始数据
     */
    public function getPoolInfo()
    {
        $total_tdb = get_bonus_rule('total_tdb');
        $total_wealth = get_bonus_rule('total_wealth');
        if ($total_tdb == 0) {
            $rate = 1;
        } else {
            $rate = number_format($total_wealth / $total_tdb, 2);
        }

        $tf_fee = get_bonus_rule('tf_fee') * 100;

        $data = [
            'total_tdb' => $total_tdb,
            'total_wealth' => $total_wealth,
            'rate' => $rate,
            'tf_fee' => $tf_fee,
        ];

        $this->apiSuccess('流动池初始数据', $data);
    }

    /**
     * 1、通兑宝兑换财富值和绿色积分；2、财富值兑换通兑宝
     */
    public function tf()
    {
        $total = input('total');
        $type = input('type', 1);

        $total_tdb = get_bonus_rule('total_tdb');
        $total_wealth = get_bonus_rule('total_wealth');
        if ($total_tdb == 0) {
            $rate = 1;
        } else {
            $rate = round($total_wealth / $total_tdb, 2);
        }

        switch ($type) {
            case 1:
                $tf_fee = get_bonus_rule('tf_fee');
                $tf_rate1 = get_bonus_rule('tf_rate1');
                $tf_rate2 = get_bonus_rule('tf_rate2');

                $wealth = $total * (1 - $tf_fee) * $rate * $tf_rate1;
                $green = $total * (1 - $tf_fee) * $rate * $tf_rate2;

                $data = ['wealth' => $wealth, 'green' => $green];
                break;
            case 2:
                $money = round($total / $rate, 4);
                $data = ['money' => $money];
                break;
        }

        $this->apiSuccess('闪兑', $data);
    }

    /**
     * 文章列表
     */
    public function documentLists()
    {
        $name = input('name', 'news');
        $cateId = Db('document_category')->where('name', $name)->value('id');
        if (!$cateId) {
            $this->apiError('参数错误！');
        }
        $lists = Document::where('status', 1)->where('category_id', $cateId)->order('id desc')->select();
        $this->apiSuccess('精选文章', $lists);
    }

    /**
     * 增加文章阅读次数
     */
    public function addView()
    {
        $id = input('id');
        Document::where('id', $id)->setInc('view');
        $this->apiSuccess('增加文章阅读次数');
    }

    /**
     * 文章详情
     */
    public function documentDetail()
    {
        $id = input('id');
        $row_info = Document::find($id);

        $this->apiSuccess('文章详情', $row_info);
    }

    /**
     * 财富值/增值通转赠的比例
     */
    public function getFlowRate()
    {
        $type = input('type', 3);
        $rate = 'flow_rate' . $type;
        $min = 'min_flow' . $type;
        $max = 'max_flow' . $type;
        $flow_rate = get_bonus_rule($rate);
        $min_flow = get_bonus_rule($min);
        $max_flow = get_bonus_rule($max);
        $this->apiSuccess('转赠的比例', ['flow_rate' => $flow_rate, 'min_flow' => $min_flow, 'max_flow' => $max_flow]);
    }
}